package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.util.ResponseData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@Api("文件上传")
@RequestMapping("/file")
public class FileController {
    @PostMapping("/imgUploadFile")
    @ApiOperation("上传照片")
    @ResponseBody
    public ResponseData imgUploadFile(MultipartFile file,  HttpServletRequest request) {
        //获取文件上传上传名 加后缀
        String filename = file.getOriginalFilename();

//        获取全路径文件夹
        String upload = request.getServletContext().getRealPath("/upload");
        System.out.println(upload);


        File file1 = new File(upload);
        //当文件夹不存在的时候创建
        if (!file1.exists()) {
            file1.mkdir();
        }
//        使用uuid和时间搓命名
        String imgName = UUID.randomUUID().toString().replaceAll("-", "") + System.currentTimeMillis() + filename;


//        文件上传的最终添加的路径
        String endFile = upload + "/" + imgName;
        try {
            file.transferTo(new File(endFile));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return ResponseData.allResponse(imgName, "上传成功", 100, 0);
    }
}
